<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row>
              <el-col :span="6">
                <el-form-item label="服务名称" prop="title">
                  <el-input v-model="queryParams.title" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="收益人" prop="title">
                  <el-input v-model="queryParams.title" placeholder="请输入收益人姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间" style="width: 308px">
                  <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                    <el-option :key="0" value="0" label="待结算"></el-option>
                    <el-option :key="1" value="1" label="已结算"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lawyer:brokerageRecord:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['lawyer:brokerageRecord:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['lawyer:brokerageRecord:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['lawyer:brokerageRecord:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="brokerageRecordList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
<!--        <el-table-column label="业务ID" align="center" prop="bizId" />-->
        <el-table-column label="服务名称" align="center" prop="title" />
        <el-table-column label="收益人" align="center" prop="nickname" />
        <el-table-column label="订单金额(元)" align="center" prop="totalAmount">
          <template #default="scope">
            <el-text>{{ scope.row.totalAmount / 100 }} 元</el-text>
          </template>
        </el-table-column>
        <el-table-column label="佣金比例" align="center" prop="firstPercent" />
        <el-table-column label="佣金(元)" align="center" prop="amount">
          <template #default="scope">
            <el-text>{{ scope.row.amount / 100 }} 元</el-text>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.status == '0'">待结算</el-tag>
            <el-tag type="success" v-else>已结算</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="冻结天数" align="center" prop="frozenDay" />
        <el-table-column label="解冻时间" align="center" prop="unfreezeTime">
        </el-table-column>
        <el-table-column label="下级分销用户" align="center" prop="sourceUserName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="立即结算" placement="top">
              <el-button link type="primary" icon="Coin" @click="handleCommission(scope.row)" v-hasPermi="['brokerage:user:commission']"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lawyer:brokerageRecord:remove']"></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改佣金记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="brokerageRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信用户ID" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入微信用户ID" />
        </el-form-item>
        <el-form-item label="业务ID" prop="bizId">
          <el-input v-model="form.bizId" placeholder="请输入业务ID" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="金额,单位分" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入金额,单位分" />
        </el-form-item>
        <el-form-item label="佣金比例" prop="firstPercent">
          <el-input v-model="form.firstPercent" placeholder="请输入佣金比例" />
        </el-form-item>
        <el-form-item label="佣金,单位分" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入佣金,单位分" />
        </el-form-item>
        <el-form-item label="冻结天数" prop="frozenDay">
          <el-input v-model="form.frozenDay" placeholder="请输入冻结天数" />
        </el-form-item>
        <el-form-item label="解冻时间" prop="unfreezeTime">
          <el-date-picker clearable
                          v-model="form.unfreezeTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择解冻时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="来源下级分销用户ID" prop="sourceUserId">
          <el-input v-model="form.sourceUserId" placeholder="请输入来源下级分销用户ID" />
        </el-form-item>
        <el-form-item label="来源下级分销用户姓名" prop="sourceUserName">
          <el-input v-model="form.sourceUserName" placeholder="请输入来源下级分销用户姓名" />
        </el-form-item>
        <el-form-item label="下级分销用户等级" prop="sourceUserLevel">
          <el-input v-model="form.sourceUserLevel" placeholder="请输入下级分销用户等级" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BrokerageRecord" lang="ts">
import { listBrokerageRecord, getBrokerageRecord, delBrokerageRecord, addBrokerageRecord, updateBrokerageRecord } from '@/api/brokerage/record';
import { BrokerageRecordVo, BrokerageRecordQuery, BrokerageRecordForm } from '@/api/brokerage/record/types';
import { commissionSettlement } from '@/api/brokerage/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const brokerageRecordList = ref<BrokerageRecordVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const brokerageRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BrokerageRecordForm = {
  id: undefined,
  wxUserId: undefined,
  bizId: undefined,
  bizType: undefined,
  title: undefined,
  totalAmount: undefined,
  firstPercent: undefined,
  amount: undefined,
  status: undefined,
  frozenDay: undefined,
  unfreezeTime: undefined,
  sourceUserId: undefined,
  sourceUserName: undefined,
  sourceUserLevel: undefined,
}
const data = reactive<PageData<BrokerageRecordForm, BrokerageRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wxUserId: undefined,
    bizId: undefined,
    bizType: undefined,
    title: undefined,
    totalAmount: undefined,
    firstPercent: undefined,
    amount: undefined,
    status: undefined,
    frozenDay: undefined,
    unfreezeTime: undefined,
    sourceUserId: undefined,
    sourceUserName: undefined,
    sourceUserLevel: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    wxUserId: [
      { required: true, message: "微信用户ID不能为空", trigger: "blur" }
    ],
    bizId: [
      { required: true, message: "业务ID不能为空", trigger: "blur" }
    ],
    bizType: [
      { required: true, message: "业务类型不能为空", trigger: "change" }
    ],
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "金额,单位分不能为空", trigger: "blur" }
    ],
    firstPercent: [
      { required: true, message: "佣金比例不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "佣金,单位分不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    frozenDay: [
      { required: true, message: "冻结天数不能为空", trigger: "blur" }
    ],
    unfreezeTime: [
      { required: true, message: "解冻时间不能为空", trigger: "blur" }
    ],
    sourceUserId: [
      { required: true, message: "来源下级分销用户ID不能为空", trigger: "blur" }
    ],
    sourceUserName: [
      { required: true, message: "来源下级分销用户姓名不能为空", trigger: "blur" }
    ],
    sourceUserLevel: [
      { required: true, message: "下级分销用户等级不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询佣金记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBrokerageRecord(proxy?.addDateRange(queryParams.value, dateRange.value));
  brokerageRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  brokerageRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BrokerageRecordVo[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加佣金记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BrokerageRecordVo) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBrokerageRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改佣金记录';
}

/** 提交按钮 */
const submitForm = () => {
  brokerageRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBrokerageRecord(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBrokerageRecord(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BrokerageRecordVo) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delBrokerageRecord(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
}

const handleCommission = async (row?: BrokerageRecordVo) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否立即结算${row?.nickname}的佣金？`).finally(() => loading.value = false);
  await commissionSettlement(_ids);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('lawyer/brokerageRecord/export', {
    ...queryParams.value
  }, `BrokerageRecord_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
